// 分页请求插件
import { reactive } from 'vue'

export function useList<T = any>(request: ApiCall<T>, query?: any) {
  /**
   * 分页数据信息
   */
  const list = reactive({
    query: query,
    page: { page: 1, size: 10 },
    data: [] as Array<T>,
    loading: false,
    finished: false
  })

  /**
   * 获取分页数据信息
   */
  const getList = async () => {
    try {
      const data = await request({ ...list.page, ...list.query })
      list.data = list.data.concat(data.lists as Array<T>)
      const total = list.page.page * list.page.size
      if (total >= data.meta.total) {
        list.finished = true
      } else {
        list.page.page++
      }
      list.loading = false
    } catch (e) {
      list.loading = false
      console.error('getList error', e)
    }
  }

  /**
   * 重置分页数据
   */
  const reset = (query?: any) => {
    list.page.page = 1
    list.page.size = 10
    list.loading = true
    list.finished = false
    list.data = []
    if (query) {
      list.query = query
    }
  }

  return {
    getList,
    list,
    reset
  }
}
